﻿using FCTIP20.Procdure;
using FCTIP20.View;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using Common;
using IP20.Procdure;

namespace FCTIP20.ViewModel
{
    internal partial class MainWindowModel
    {
        private void Wait(int millseconds)
        {
            Stopwatch sw = Stopwatch.StartNew();
            while (sw.ElapsedMilliseconds < millseconds)
            {
                if (MachineStatus == MachineStatus.Stop)
                    EmStop();
            }
        }

        // TCP客户端实例
        private Tcp_Client tcp_Client;

        // 存储IP地址和端口
        private string ip = "127.0.0.1";

        private int port = 9001;
        private string msg;
        private string zhilin_1 = "$Initialize_";//指定打印模板
        private string zhilin_2 = "$Data_";//传输打印内容
        private string zhilin_3 = "$MarkStart_";//开始打印
        private string zhilin_4 = "$MarkStop_";//停止打印
        private string EAN = "";
        private string PrintMobanName = "";
        private string SN = "";
        private string MAC = "";
        private string HW = "";
        private string OHname = "";
        private bool PrintIsOk = false;
        private static string baseDirectory = "D://Data";

        #region ListView数据模型

        private ObservableCollection<ListViewDataArr> _textList;

        public ObservableCollection<ListViewDataArr> TextList
        {
            get { return _textList; }
            set { _textList = value; this.DoNotify(); }
            //this.DoNotify()实现INotifyPropertyChanged接口
        }

        public class ListViewDataArr
        {
            public string Name { get; set; }
            public string Status { get; set; }
            public bool StateIsOk { get; set; }
        }

        #endregion ListView数据模型

        private void NewContentView()
        {
            try
            {
                ContentChecked = new ContentView();
            }
            catch (Exception ex)
            {
                EmStop();
            }
        }

        private bool StartPrint()
        {
            try
            {
                // 绑定委托到日志显示方法
                tcp_Client = new Tcp_Client(ip, port);
                tcp_Client.MsgLog += new EventHandler<EventArgs>(ShowClientMsg);
                tcp_Client.resultMsg += new EventHandler<EventArgs>(ReceiveData);

                // 尝试连接服务器
                if (tcp_Client.ConnectServer())
                {
                    MachineStatus = MachineStatus.Running;
                    Log = "镭雕机连接成功";
                    AddData(true, "镭雕机连接成功");
                    return true;
                }
                else
                {
                    EmStop();
                    AddData(false, "镭雕机连接失败!");
                    return false;
                }
            }
            catch (Exception ex)
            {
                EmStop();
                Log = "链接镭雕机出错！";
                AddData(false, "链接镭雕机出错！");
                return false;
            }
        }

        /// <summary>
        /// 自动模式
        /// </summary>
        /// <param name="PrintMobanName">镭雕机模板名</param>
        /// <param name="autoChannel">是否自动</param>
        private void StartContent(string PrintMoban_Name)
        {
            //手动模式前置识别工位1
            bool AutoStartOne = Global.PQW_IO.GetDI((int)DOslaveID.slaveID, (int)DIDefine.Auto);//重新识别模式
            if (!AutoStartOne)
            {
                //false为手动
                //只需检测工位一有无产品
                bool work1One = Global.PQW_IO.GetDI((int)DOslaveID.slaveID, (int)DIDefine.Work1);
                if (!work1One)
                {
                    MachineStatus = MachineStatus.Idle;
                    Log = "未检测到物料！";
                    AddData(false, "未检测到物料！");
                    Thread.Sleep(1000);
                    return;
                }
            }
            //检测到物料
            MachineStatus = MachineStatus.Running;
            EAN = "";
            SN = "";
            MAC = "";
            HW = "";
            OHname = "";
            PrintMobanName = "";
            bool AutoStart = true;
            PrintMobanName = PrintMoban_Name;
            Stopwatch sw = Stopwatch.StartNew();
            Task.Run(() =>
            {
                while (AutoStart)
                {
                    try
                    {
                        //初始化灯光
                        Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.GreenLight, true);
                        Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.YellowLight, false);

                        if (MachineStatus == MachineStatus.Stop)
                        {
                            EmStop();
                            break;
                        }
                        Log = "等待工位1放料完成";
                        bool work1 = Global.PQW_IO.GetDI((int)DOslaveID.slaveID, (int)DIDefine.Work1);
                        if (!work1)
                        {
                            Log = "未检测到物料";
                            AddData(false, "未检测到物料！");
                            Thread.Sleep(1000);
                            continue;
                        }
                        Log = "工位1成功检测到物料！！";

                        Thread.Sleep(500);
                        if (Global.PQW_IO.GetDI((int)DOslaveID.slaveID, (int)DIDefine.Auto))
                        {
                            Log = "10ms后分割器开始动作";
                            Thread.Sleep(10000);
                        }
                        if (MachineStatus == MachineStatus.Stop)
                        {
                            EmStop();
                            return;
                        }
                        bool RevolveBase = Global.PQW_IO.GetDI((int)DOslaveID.slaveID, (int)DIDefine.RevolveBase);
                        bool RevolveBase1 = Global.PQW_IO.GetDI((int)DOslaveID.slaveID, (int)DIDefine.RevolveBase1);
                        bool AriWorkBase = Global.PQW_IO.GetDI((int)DOslaveID.slaveID, (int)DIDefine.AriWorkBase);
                        if (RevolveBase == false || RevolveBase1 == false || AriWorkBase == false)
                        {
                            Log = "气缸不在原位!";
                            AddData(false, "气缸不在原位！请检查！！");
                            EmStop();
                            return;
                        }
                        Global.BreakD = true;
                        Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.DOBreakUp, true);//分割器动作
                        Log = "分割器动作";
                        Thread.Sleep(1000);

                        while (true)
                        {
                            //bool BreakUp = Global.PQW_IO.GetDI((int)DOslaveID.slaveID, (int)DIDefine.BreakUp);
                            //分割器是否到位
                            if (Global.BreakUpStats)
                            {
                                Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.DOBreakUp, false);//分割器停止
                                Log = "分割器到位停止";
                                Global.BreakUpStats = false;
                                Global.BreakD = false;
                                Global.BreakUpStatsNum = 0;
                                break;
                            }
                            if (MachineStatus == MachineStatus.Stop)
                            {
                                EmStop();
                                return;
                            }
                            Thread.Sleep(300);
                        }

                        if (MachineStatus == MachineStatus.Stop)
                        {
                            EmStop();
                            return;
                        }
                        if (MachineStatus == MachineStatus.Stop)
                        {
                            EmStop();
                            return;
                        }
                        Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.DOAriWorkC, true);//插线气缸动作
                        Log = "插线气缸动作";
                        if (MachineStatus == MachineStatus.Stop)
                        {
                            EmStop();
                            return;
                        }
                        Thread.Sleep(2000);
                        //Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.OHlink, true);//耦合器连接
                        Log = "耦合器连接";
                        if (MachineStatus == MachineStatus.Stop)
                        {
                            EmStop();
                            return;
                        }
                        Thread.Sleep(1000);
                        Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.Power, true);//供电
                        Log = "供电";
                        Wait(5000);
                        if (MachineStatus == MachineStatus.Stop)
                        {
                            EmStop();
                            return;
                        }

                        var allcoms = SerialPort.GetPortNames();
                        if (!allcoms.Contains($"COM{Config.ProductCom}"))
                        {
                            Log = "耦合器COM口搜索失败!";
                            AddData(false, "耦合器COM口搜索失败!");
                            EmStop();
                            return;
                        }
                        else
                        {
                            Log = "耦合器COM口搜索成功";
                            AddData(true, "耦合器COM口搜索成功!");
                        }
                        bool FactoryStatus = false;
                        //工厂耦合器链接,弃用
                        //FactoryApp fctDll = new FactoryApp();
                        //ObservableCollection<FactoryArray> FCTArray = fctDll.Main(Config.ProductCom);//12是COM口
                        IP20Factory fctDll = new IP20Factory(Config.ProductCom);
                        fctDll.ComApi = FactoryCommunicationApi.FACTORY_SERIAL_API;
                        fctDll.Connect();
                        fctDll.ScanDevice();
                        ObservableCollection<FactoryModuleScanDataConvert> FCTArray = new ObservableCollection<FactoryModuleScanDataConvert>(fctDll.modules);

                        if (PrintMobanName == "模块")
                        {
                            if (FCTArray.Count != 2)
                            {
                                Log = "请放置一个模块!";
                                AddData(false, "请放置一个模块！");
                                EmStop();
                                return;
                            }
                        }
                        else if (PrintMoban_Name == "耦合器")
                        {
                            if (FCTArray.Count > 1)
                            {
                                Log = "耦合器不能带模块!";
                                AddData(false, "耦合器不能带模块！");
                                EmStop();
                                return;
                            }
                        }
                        Log = "读取数据";
                        if (FCTArray.Count == 0)
                        {
                            Log = $"系统连接耦合器失败";
                            AddData(false, "系统连接耦合器失败！");
                            //失败扫描3次
                            for (int i = 1; i < 4; i++)
                            {
                                Log = $"系统尝试第{i}重连耦合器";
                                //FCTArray = fctDll.Main(Config.ProductCom);//12是COM口
                                fctDll.Connect();
                                fctDll.ScanDevice();
                                FCTArray = new ObservableCollection<FactoryModuleScanDataConvert>(fctDll.modules);
                                if (FCTArray.Count > 0)
                                {
                                    break;
                                }
                                Wait(500);
                            }
                            if (FCTArray.Count == 0)
                            {
                                EmStop();
                                Log = "耦合器扫描失败!";
                                AddData(false, "耦合器扫描失败！");
                                return;
                            }
                        }
                        //耦合器/模块链接状态
                        FactoryStatus = true;
                        FactoryModuleScanDataConvert ListSN = FactorySelectArray(FCTArray, PrintMobanName);//根据选择类型提取模块/耦合器数据

                        SN = ListSN.sn;
                        MAC = ListSN.mac;
                        HW = ListSN.hwVersion;
                        OHname = ListSN.name;
                        if ((OHname != "8930P" && OHname != "JQ8930E") && PrintMobanName != "模块")
                        {
                            Log = "选择的打印模板与耦合器不一致!";
                            AddData(false, "选择的打印模板与耦合器不一致！");
                            EmStop();
                            return;
                        }
                        if (SN.Length != 15 || MAC.Length != 17)
                        {
                            AddData(false, "系统读取SN和MAC错误");
                            Log = $"系统读取SN和MAC错误";
                            //失败扫描3次
                            for (int i = 1; i < 4; i++)
                            {
                                Log = $"系统尝试第{i}读取SN和MAC";
                                //FCTArray = fctDll.Main(12);//12是COM口
                                fctDll.Connect();
                                fctDll.ScanDevice();
                                FCTArray = new ObservableCollection<FactoryModuleScanDataConvert>(fctDll.modules);
                                SN = ListSN.sn;
                                MAC = ListSN.mac;
                                if (SN.Length == 15 || MAC.Length == 17)
                                {
                                    break;
                                }
                                Wait(500);
                            }
                            if (SN.Length != 15 || MAC.Length != 17)
                            {
                                Log = "SN或MAC读取失败!";
                                AddData(false, "SN或MAC读取失败！");
                                EmStop();
                                return;
                            }
                        }

                        //验证EAN
                        if (PrintMoban_Name == "耦合器")
                        {
                            EAN = ReslutEAN(OHname);
                        }
                        else
                        {
                            EAN = ReslutEAN_model(OHname);//根据返回模块型号查询EAN
                        }
                        if (string.IsNullOrEmpty(EAN))
                        {
                            Log = "查询EAN失败!";
                            AddData(false, "查询EAN失败！");
                            EmStop();
                            return;
                        }
                        if (MachineStatus == MachineStatus.Stop)
                        {
                            EmStop();
                            return;
                        }
                        //竖立打码，金属感应灯亮Y0控制工位2翻转
                        //检测当前正在打标工位true为2工位和false为1工位
                        bool workMake = Global.PQW_IO.GetDI((int)DOslaveID.slaveID, (int)DIDefine.WorkMake);

                        if (FactoryStatus)
                        {
                            PrintIsOk = false;
                            if (MachineStatus == MachineStatus.Stop)
                            {
                                AddData(false, "设备急停！");
                                EmStop();
                                return;
                            }
                            Thread.Sleep(500);
                            Log = "等待打码";
                            if (OHname == "")
                            {
                                AddData(false, "读取模块名错误！！");
                                EmStop();
                                return;
                            }
                            //string PrintMes = GetPrintName(OHname);
                            if (OHname == "8930P" && PrintMobanName == "耦合器")
                            {
                                printMarkStart("8930P");//放平打码
                                Thread.Sleep(4000);
                                int p = 0;
                                while (true)
                                {
                                    if (MachineStatus == MachineStatus.Stop)
                                    {
                                        EmStop();
                                        break;
                                    }
                                    if (PrintIsOk == true)
                                    {
                                        break;
                                    }
                                    else if (p > 50 && PrintIsOk == false)
                                    {
                                        EmStop();
                                        Log = "打码失败!";
                                        AddData(false, "打码失败！");
                                        break;
                                    }
                                    Thread.Sleep(400);
                                    p++;
                                }

                                if (PrintIsOk == true)
                                {
                                    PrintIsOk = false;
                                    Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.DOAriWorkC, false);
                                    Wait(500);
                                    if (workMake)
                                    {
                                        Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.RevolveAri1, true);
                                    }
                                    else
                                    {
                                        Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.RevolveAri, true);
                                    }
                                    Wait(1000);
                                    if (MachineStatus == MachineStatus.Stop)
                                    {
                                        EmStop();
                                        return;
                                    }
                                    bool daowei = false;
                                    if (workMake)
                                    {
                                        daowei = Global.PQW_IO.GetDI((int)DOslaveID.slaveID, (int)DIDefine.RevolveReach1);
                                    }
                                    else
                                    {
                                        daowei = Global.PQW_IO.GetDI((int)DOslaveID.slaveID, (int)DIDefine.RevolveReach);
                                    }
                                    if (!daowei)
                                    {
                                        EmStop();
                                        return;
                                    }
                                    PrintIsOk = false;
                                    printMarkStart("8930PPlus");//竖立打码
                                    Thread.Sleep(4000);
                                }
                            }
                            else if (OHname == "JQ8930E" && PrintMobanName == "耦合器")
                            {
                                printMarkStart("8930E");
                            }
                            else if (OHname != "JQ8930E" && OHname != "8930P" && PrintMobanName == "模块")
                            {
                                printMarkStart("模块");
                            }
                            else
                            {
                                Log = "打标目标不明确";
                                AddData(false, "打标目标不明确！");
                                EmStop();
                                return;
                            }
                            int j = 0;
                            while (true)
                            {
                                if (MachineStatus == MachineStatus.Stop)
                                {
                                    EmStop();
                                    break;
                                }
                                if (PrintIsOk == true)
                                {
                                    string MESfileName = $"D:\\Result\\";
                                    if (!Directory.Exists(MESfileName))
                                    {
                                        Directory.CreateDirectory(MESfileName);
                                    }
                                    string EndTime = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
                                    string MESfileValue = $"{SN}_{EndTime}_OK.txt";
                                    MESfileName = MESfileName + MESfileValue;
                                    //写入运行日志
                                    using (FileStream fs = File.Create(MESfileName))
                                    {
                                        // 可以在这里写入一些内容，例如：
                                        byte[] info = new UTF8Encoding(true).GetBytes($"ProductName:{OHname},ENA:{EAN},SN:{SN},EndTime:{EndTime},MAC:{MAC},OK");
                                        fs.Write(info, 0, info.Length);
                                    }
                                    OkCount++;
                                    MachineStatus = MachineStatus.Idle;
                                    Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.YellowLight, true);
                                    Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.GreenLight, false);
                                    Log = "打码完成";
                                    fctDll.Close();
                                    Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.OHlink, false);
                                    Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.Power, false);
                                    Log = "等待断开连接器、24V供电";
                                    Thread.Sleep(2000);
                                    Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.DOAriWorkC, false);
                                    Wait(500);
                                    if (workMake)
                                    {
                                        Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.RevolveAri1, false);
                                    }
                                    else
                                    {
                                        Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.RevolveAri, false);
                                    }
                                    Log = "等待复位气缸";
                                    Thread.Sleep(1000);
                                    bool RevolveAriStatus = false;
                                    if (workMake)
                                    {
                                        RevolveAriStatus = Global.PQW_IO.GetDI((int)DOslaveID.slaveID, (int)DIDefine.RevolveBase1);
                                    }
                                    else
                                    {
                                        RevolveAriStatus = Global.PQW_IO.GetDI((int)DOslaveID.slaveID, (int)DIDefine.RevolveBase);
                                    }
                                    bool ariWorkBase = Global.PQW_IO.GetDI((int)DOslaveID.slaveID, (int)DIDefine.AriWorkBase);
                                    if (!RevolveAriStatus || !ariWorkBase)
                                    {
                                        Log = "断开下压气缸、插线气缸、连接器、24V供电，失败!";
                                        AddData(false, "断开下压气缸、插线气缸、连接器、24V供电，失败！");
                                        EmStop();
                                        break;
                                    }
                                    break;
                                }
                                if (j > 50 && PrintIsOk == false)
                                {
                                    EmStop();
                                    Log = "打码失败!";
                                    AddData(false, "打码失败！");
                                    break;
                                }
                                Thread.Sleep(400);
                                j++;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        AddData(false, ex.ToString());
                        Log = ex.ToString();

                        EmStop();
                    }
                    Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.Power, false);
                    Thread.Sleep(1000);
                    Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.DOAriWorkC, false);
                    Log = "正在生产报告";
                    OutExcel(sw);
                    AutoStart = Global.PQW_IO.GetDI((int)DOslaveID.slaveID, (int)DIDefine.Auto);//重新识别模式
                    if (!AutoStart)
                    {
                        Global.IsBusy = false;
                        Log = "已切换到手动，退出轮询";
                        //暂时加
                        MachineStatus = MachineStatus.Idle;
                        AddData(true, "打标完成");
                        break;
                    }
                    Log = "5ms后开始轮询";
                    Thread.Sleep(5000);
                }
            });
        }

        //public string GetPrintName(string name)
        //{
        //    switch (name)
        //    {
        //        //case ""
        //    }
        //}

        private void printMarkStart(string PMobanName)
        {
            try
            {
                //需要判断当前工位
                if (MachineStatus == MachineStatus.Stop)
                {
                    EmStop();
                    return;
                }
                //复位后在启动重新判断连接
                if (!tcp_Client.ConnectServer())
                {
                    ContentChecked = new ContentView();
                    // 绑定委托到日志显示方法
                    tcp_Client = new Tcp_Client(ip, port);
                    tcp_Client.MsgLog += new EventHandler<EventArgs>(ShowClientMsg);
                    tcp_Client.resultMsg += new EventHandler<EventArgs>(ReceiveData);
                }
                if (tcp_Client.ConnectServer())
                {
                    if (MachineStatus == MachineStatus.Stop)
                    {
                        EmStop();
                        return;
                    }

                    string appendstr = "";
                    //检测当前正在打标工位true为2工位和false为1工位
                    bool workMake = Global.PQW_IO.GetDI((int)DOslaveID.slaveID, (int)DIDefine.WorkMake);
                    if (workMake)
                    {
                        appendstr = "2";
                        AddData(true, "当前正在打印2工位");
                    }
                    else
                    {
                        appendstr = "1";
                        AddData(true, "当前正在打印1工位");
                    }

                    string SendComMoban = "";
                    string SendComData = "";
                    if (PMobanName == "8930E" || PMobanName == "8930P")
                    {
                        SendComMoban = zhilin_1 + "JQ" + PMobanName + appendstr;
                    }
                    else if (PMobanName == "模块")
                    {
                        SendComMoban = zhilin_1 + "JQ8930MODEL" + appendstr;
                    }
                    else if (PMobanName == "8930PPlus")
                    {
                        SendComMoban = zhilin_1 + "JQ" + PMobanName + appendstr;
                    }
                    else
                    {
                        Log = "请明确打标模板!";
                        AddData(false, "请明确打标模板!");
                        EmStop();
                        return;
                    }

                    tcp_Client.SendToServer(SendComMoban);
                    AddData(true, "调用打印模板" + PMobanName);
                    Log = "使用模板";
                    Thread.Sleep(500);
                    if (MachineStatus == MachineStatus.Stop)
                    {
                        EmStop();
                        return;
                    }
                    if (PMobanName == "8930E" || PMobanName == "8930P")
                    {
                        SendComData = zhilin_2 + $"{EAN}" + " " + $"{SN},{SN},{HW}";
                        //SendComData = zhilin_2 + $"{EAN}"+" "+$"{SN};{SN};{HW}";
                        //SendComData = zhilin_2 + $"{EAN}" + "," + $"{SN}";
                    }
                    else if (PMobanName == "8930PPlus")
                    {
                        SendComData = zhilin_2 + $"{MAC}";
                    }
                    else if (PMobanName == "模块")
                    {
                        SendComData = zhilin_2 + $"{EAN}" + " " + $"{SN},{SN},{HW}";
                    }
                    else
                    {
                        Log = "请明确打标模板!";
                        EmStop();
                        return;
                    }
                    //SendCom = zhilin_2 + $"{sn};{mac}";
                    tcp_Client.SendToServer(SendComData);
                    Thread.Sleep(500);
                    AddData(true, "SN：" + SN);
                    AddData(true, "MAC：" + MAC);
                    if (MachineStatus == MachineStatus.Stop)
                    {
                        EmStop();
                        return;
                    }
                    tcp_Client.SendToServer(zhilin_3);
                    AddData(true, "正在打码");
                    Thread.Sleep(1000);

                    if (MachineStatus == MachineStatus.Stop)
                    {
                        EmStop();
                        return;
                    }
                }
                else
                {
                    //复位启动
                    EmStop();
                    AddData(false, "镭雕机连接失败");
                    return;
                }
            }
            catch (Exception ex)
            {
                AddData(false, "发送出错");
                NgCount++;
                EmStop();
                Log = "发送出错";
            }
        }

        /// <summary>
        /// 查询耦合器EAN
        /// </summary>
        /// <param name="Mname"></param>
        /// <returns></returns>
        public string ReslutEAN(string Mname)
        {
            var PRINT = Config.OuheConfigsList;
            foreach (var config in PRINT)
            {
                if (config.MoBanName == Mname)
                {
                    EAN = config.EANValue;
                }
            }
            return EAN;
        }

        /// <summary>
        /// 查询模块EAN
        /// </summary>
        /// <param name="Mname"></param>
        /// <returns></returns>
        public string ReslutEAN_model(string Mname)
        {
            var PRINT = Config.ModelListConfigs;
            string EAN = "";
            foreach (var config in PRINT)
            {
                if (config.ModelName == Mname)
                {
                    EAN = config.EANValue;
                }
            }
            return EAN;
        }

        public void stopMark()
        {
            if (tcp_Client != null)
            {
                if (tcp_Client.ConnectServer())
                {
                    tcp_Client.SendToServer(zhilin_4);
                    Log = "终止打标!";
                }
            }
        }

        public void AddData(bool IsOK, string TitleName)
        {
            string status = "NG";
            if (IsOK)
            {
                status = "OK";
            }
            //更新UI
            Application.Current.Dispatcher.Invoke(() =>
          {
              TextList.Add(new ListViewDataArr { StateIsOk = IsOK, Name = TitleName, Status = status });
          });
        }

        //处理提示信息
        public void ShowClientMsg(object sender, EventArgs e)
        {
            string str = sender.ToString();
            if (!string.IsNullOrEmpty(str))
            {
                string[] stringArray = str.Split('-');
                Log = $"{stringArray[1]}:{stringArray[0]}";
            }
        }

        //处理回调
        public void ReceiveData(object sender, EventArgs e)
        {
            string str = sender.ToString();
            if (!string.IsNullOrEmpty(str))
            {
                string[] stringArray = str.Split('-');
                Log = $"{stringArray[1]}:{stringArray[0]}";
                if (stringArray[1] == "返回信息")
                {
                    if (stringArray[0].Contains("$MarkStart_OK"))
                    {
                        PrintIsOk = true;
                    }
                    else if (stringArray[0].Contains("$Initialize_ERROR") || stringArray[0].Contains("$Data_ERROR"))
                    {
                        AddData(false, "镭雕机数据反馈异常");
                        EmStop();
                        PrintIsOk = false;
                    }
                }
            }
        }

        public FactoryModuleScanDataConvert FactorySelectArray(ObservableCollection<FactoryModuleScanDataConvert> arr, string FCTtype)
        {
            //FCTtype = FACTORY_COUPLER_MODULE耦合器,FACTORY_SLAVE_MODULE//子模块
            FactoryModuleScanDataConvert arrArray = new FactoryModuleScanDataConvert();
            foreach (var item in arr)
            {
                if (item.type == FactoryModuleType.FACTORY_COUPLER_MODULE && (FCTtype == "耦合器"))
                {
                    arrArray = item;
                    break;
                }
                else if (item.type == FactoryModuleType.FACTORY_SLAVE_MODULE)
                {
                    arrArray = item;
                    break;
                }
            }
            return arrArray;
        }

        /// <summary>
        /// 紧急停止
        /// </summary>
        private void EmStop()
        {
            try
            {
                if (MachineStatus != MachineStatus.Stop)
                {
                    MachineStatus = MachineStatus.Stop;
                    Global.PQW_IO.SetDO((int)DOslaveID.slaveID, (int)DODefine.DOAriWorkC, false);
                    Thread.Sleep(50);
                    Global.PQW_IO.OffAll(1);
                    Log = "急停!";
                    NgCount++;
                    Global.IsBusy = false;
                    Global.PQW_IO.SetDO(1, (int)DODefine.RedLight, true);
                    Thread.Sleep(500);
                    Global.PQW_IO.SetDO(1, (int)DODefine.RedLight, false);
                }
            }
            catch (Exception e)
            {
                Mylog.Error(e);
                AddData(false, e.Message);
            }

            return;
        }

        public void OutExcel(Stopwatch sw)
        {
            //生成测试报告
            var directory = $"{baseDirectory}//{DateTime.Now.ToString("yyyyMMdd")}//{OHname}";
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            string time = DateTime.Now.ToString("yyyyMMddHHmmss");
            GenerateReport($"{directory}//{time}_Total.xlsx");
            Log = $"报告已生成，耗时{sw.ElapsedMilliseconds / 1000}秒";
        }

        private void GenerateReport(string filePath)
        {
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
            FileInfo excelFile = new FileInfo(filePath);
            using (var package = excelFile.Exists ?
                new ExcelPackage(excelFile) :
                new ExcelPackage())
            {
                // 获取或创建工作表
                var worksheet = package.Workbook.Worksheets.FirstOrDefault() ??
                              package.Workbook.Worksheets.Add("Sheet1");
                {
                    if (!excelFile.Exists)
                    {
                        // 设置列头
                        worksheet.Cells[1, 1].Value = "打标时间";
                        worksheet.Cells[1, 2].Value = "产品名称";
                        worksheet.Cells[1, 3].Value = "硬件版本号";
                        worksheet.Cells[1, 4].Value = "SN码";
                        worksheet.Cells[1, 5].Value = "EAN码";
                        worksheet.Cells[1, 6].Value = "MAC码";
                        worksheet.Cells[1, 7].Value = "打标状态";
                        // 设置列头样式
                        using (var range = worksheet.Cells["A1:P1"])
                        {
                            range.Style.Font.Bold = true;
                            range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                            range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
                        }
                        // 自动调整列宽
                        worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
                    }
                    //添加数据
                    worksheet.Cells[2, 1].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); ;
                    worksheet.Cells[2, 2].Value = OHname;
                    worksheet.Cells[2, 3].Value = HW;
                    worksheet.Cells[2, 4].Value = SN;
                    worksheet.Cells[2, 5].Value = EAN;
                    worksheet.Cells[2, 6].Value = MAC;
                    worksheet.Cells[2, 7].Value = PrintIsOk.ToString();

                    // 保存文件
                    package.SaveAs(excelFile);
                }
            }
        }
    }
}